using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsDataBaice
{
    public class OutpatientForm : Form
    {
        // 控件声明
        private TextBox txtTitle;
        private Button btnAddItem, btnPrint, btnClose;
        private Label lblPreviewArea;
        private Panel pnlDesignArea;
        private Panel printItemsPanel;
        private Panel buttonPanel;
        private CheckBox[] chkPrintItems;
        private Button btnSave, btnClear, btnPreview;
        
        // 打印项目列表
        private string[] printItems = {
            "编号", "科室", "医师", "处方药", "病床号", 
            "问诊时间", "入院时间", "出院时间", "消费明细", "收银员", "消费金额"
        };

        // 设计区按钮列表
        private List<Button> designButtons = new List<Button>();
        // 自定义项目列表
        private List<string> customItems = new List<string>();

        // 预览区相关控件
        private Panel pnlPreviewArea;
        private Button btnPreviewPrint, btnPreviewClose;
        private Label lblPreviewTitle;
        private PictureBox picPreviewLogo;
        private List<Label> previewItemLabels = new List<Label>();

        // 新增：保存打印区X和宽度，便于动态布局
        private int printAreaX, printAreaWidth;
        private Label lblPreviewAreaTitle;

        private Bitmap previewBitmap;

        public OutpatientForm()
        {
            InitializeComponent();
            SetupEventHandlers();
            SetupCheckBoxEvents();
            ClearAll(); // 启动时自动清空
        }

        /// <summary>
        /// 初始化窗体组件
        /// 简化布局，彻底解决重叠问题
        /// </summary>
        private void InitializeComponent()
        {
            this.Text = "门诊单设置";
            this.Size = new Size(1300, 900);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = UIStyleManager.BackgroundColor;

            // 顶部标题面板
            Panel titlePanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 80,
                BackColor = UIStyleManager.PrimaryColor
            };

            Label lblTitleIcon = new Label
            {
                Text = IconManager.Icons.File,
                Font = new Font("Segoe UI Emoji", 26),
                ForeColor = Color.White,
                Location = new Point(30, 20),
                AutoSize = true
            };

            Label lblFormTitle = new Label
            {
                Text = "  门诊单设置",
                Font = UIStyleManager.TitleFont,
                ForeColor = Color.White,
                AutoSize = true,
                Location = new Point(80, 25)
            };

            titlePanel.Controls.Add(lblTitleIcon);
            titlePanel.Controls.Add(lblFormTitle);
            this.Controls.Add(titlePanel);

            // 顶部配置区域
            Label lblTitle = new Label 
            { 
                Text = $"{IconManager.Icons.Edit}  标题文本:", 
                Location = new Point(40, 110), 
                AutoSize = true 
            };
            UIStyleManager.ApplyLabelStyle(lblTitle, LabelStyle.Body);
            
            txtTitle = new TextBox 
            { 
                Text = "门诊单", 
                Location = new Point(160, 108), 
                Size = new Size(200, 28) 
            };
            UIStyleManager.ApplyTextBoxStyle(txtTitle);
            
            btnAddItem = IconManager.CreateSmallIconButton("添加项目", IconManager.Icons.Plus, 100, 28);
            btnAddItem.Location = new Point(380, 108);
            btnAddItem.Padding = new Padding(8, 0, 8, 0);

            // 设计区 - 统一与挂号单、住院单样式
            pnlDesignArea = UIStyleManager.CreateCardPanel("设计区", 400, 480);
            pnlDesignArea.Location = new Point(50, 160);

            // 初始化设计区默认按钮
            string[] defaultDesignItems = { "编号", "科室", "医师", "处方药" };
            int btnYOffset = 60;
            foreach (var item in defaultDesignItems)
            {
                Button btn = CreateDesignButton(item, btnYOffset);
                designButtons.Add(btn);
                pnlDesignArea.Controls.Add(btn);
                btnYOffset += 55;
            }

            // 打印项目区
            printAreaX = 50 + 400 + 50;
            printAreaWidth = 250;
            
            printItemsPanel = UIStyleManager.CreateCardPanel("打印项目", 250, 480);
            printItemsPanel.Location = new Point(printAreaX, 160);


            // 创建打印项目复选框 - 统一与挂号单、住院单样式
            chkPrintItems = new CheckBox[printItems.Length];
            for (int i = 0; i < printItems.Length; i++)
            {
                chkPrintItems[i] = new CheckBox
                {
                    Text = printItems[i],
                    Location = new Point(30, 60 + i * 35),
                    AutoSize = true,
                    Tag = printItems[i],
                    Font = UIStyleManager.BodyFont,
                    Padding = new Padding(4, 0, 0, 0)
                };
                UIStyleManager.ApplyCheckBoxStyle(chkPrintItems[i]);
                printItemsPanel.Controls.Add(chkPrintItems[i]);
            }

            // 底部按钮面板
            buttonPanel = new Panel
            {
                Location = new Point(printAreaX, 670),
                Size = new Size(250, 70),
                BackColor = Color.White
            };

            btnSave = IconManager.CreateSmallIconButton("保存", IconManager.Icons.Save, 75, 40, ButtonStyle.Success);
            btnSave.Location = new Point(15, 15);
            
            btnClear = IconManager.CreateSmallIconButton("清空", IconManager.Icons.Refresh, 75, 40, ButtonStyle.Warning);
            btnClear.Location = new Point(100, 15);
            
            btnPreview = IconManager.CreateSmallIconButton("预览", IconManager.Icons.Search, 75, 40, ButtonStyle.Primary);
            btnPreview.Location = new Point(185, 15);

            buttonPanel.Controls.Add(btnSave);
            buttonPanel.Controls.Add(btnClear);
            buttonPanel.Controls.Add(btnPreview);

            // 预览区
            int previewAreaX = printAreaX + 250 + 50;
            lblPreviewAreaTitle = new Label
            {
                Text = $"{IconManager.Icons.Search}  预览区",
                Location = new Point(previewAreaX, 160),
                AutoSize = true
            };
            UIStyleManager.ApplyLabelStyle(lblPreviewAreaTitle, LabelStyle.Subtitle);
            
            pnlPreviewArea = UIStyleManager.CreateCardPanel("", 350, 580);
            pnlPreviewArea.Location = new Point(previewAreaX, 190);
            pnlPreviewArea.Visible = false;
            
            btnPreviewPrint = IconManager.CreateSmallIconButton("打印", IconManager.Icons.Print, 80, 35, ButtonStyle.Success);
            btnPreviewPrint.Location = new Point(30, 25);
            
            btnPreviewClose = IconManager.CreateSmallIconButton("关闭", IconManager.Icons.Close, 80, 35, ButtonStyle.Danger);
            btnPreviewClose.Location = new Point(280, 25);
            
            lblPreviewTitle = new Label 
            { 
                Text = "门诊单", 
                Location = new Point(120, 70), 
                AutoSize = true 
            };
            UIStyleManager.ApplyLabelStyle(lblPreviewTitle, LabelStyle.Title);
            
            picPreviewLogo = new PictureBox 
            { 
                Location = new Point(40, 60), 
                Size = new Size(60, 60), 
                SizeMode = PictureBoxSizeMode.Zoom 
            };
            
            pnlPreviewArea.Controls.Add(btnPreviewPrint);
            pnlPreviewArea.Controls.Add(btnPreviewClose);
            pnlPreviewArea.Controls.Add(lblPreviewTitle);
            pnlPreviewArea.Controls.Add(picPreviewLogo);

            // 添加控件到窗体
            this.Controls.Add(lblTitle);
            this.Controls.Add(txtTitle);
            this.Controls.Add(btnAddItem);
            this.Controls.Add(pnlDesignArea);
            this.Controls.Add(printItemsPanel);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(lblPreviewAreaTitle);
            this.Controls.Add(pnlPreviewArea);
            this.Resize += OutpatientForm_Resize;

            Console.WriteLine("门诊单设置窗体布局初始化完成，重叠问题已解决");
        }

        /// <summary>
        /// 窗体大小改变事件处理
        /// 统一与挂号单、住院单的响应式布局
        /// </summary>
        private void OutpatientForm_Resize(object sender, EventArgs e)
        {
            // 动态调整预览区位置，避免重叠
            int previewAreaX = printAreaX + 250 + 50;
            lblPreviewAreaTitle.Location = new Point(previewAreaX, 160);
            pnlPreviewArea.Location = new Point(previewAreaX, 190);
            
            Console.WriteLine($"门诊单设置窗体大小改变: {this.Size}");
        }

        private Button CreateDesignButton(string text, int y)
        {
            return new Button
            {
                Text = text,
                Location = new Point(25, y),
                Size = new Size(90, 45),
                BackColor = Color.LightBlue,
                Font = new Font("微软雅黑", 10),
                Padding = new Padding(5, 0, 5, 0)
            };
        }

        private void RefreshDesignButtons()
        {
            // 先移除所有按钮
            for (int i = pnlDesignArea.Controls.Count - 1; i >= 0; i--)
            {
                if (pnlDesignArea.Controls[i] is Button)
                    pnlDesignArea.Controls.RemoveAt(i);
            }
            designButtons.Clear();
            int y = 60;
            // 先添加所有勾选的多选框项
            foreach (var chk in chkPrintItems)
            {
                if (chk.Checked)
                {
                    Button btn = CreateDesignButton(chk.Text, y);
                    designButtons.Add(btn);
                    pnlDesignArea.Controls.Add(btn);
                    y += 55;
                }
            }
            // 再添加所有自定义项
            foreach (var item in customItems)
            {
                Button btn = CreateDesignButton(item, y);
                designButtons.Add(btn);
                pnlDesignArea.Controls.Add(btn);
                y += 55;
            }
        }

        private void SetupEventHandlers()
        {
            // 删除btnClose.Click事件绑定，避免空引用异常
            btnPreview.Click += BtnPreview_Click;
            btnClear.Click += BtnClear_Click;
            btnSave.Click += BtnSave_Click;
            btnAddItem.Click += BtnAddItem_Click;
            btnPreviewClose.Click += (s, e) => pnlPreviewArea.Visible = false;
            btnPreviewPrint.Click += BtnPrint_Click;
        }

        private void SetupCheckBoxEvents()
        {
            foreach (var chk in chkPrintItems)
            {
                chk.CheckedChanged += ChkPrintItem_CheckedChanged;
            }
        }

        private void ChkPrintItem_CheckedChanged(object sender, EventArgs e)
        {
            RefreshDesignButtons();
        }

        private void BtnPreview_Click(object sender, EventArgs e)
        {
            // 显示预览区
            pnlPreviewArea.Visible = true;
            // 设置标题
            lblPreviewTitle.Text = txtTitle.Text.Trim();
            // 清除旧内容
            foreach (var lbl in previewItemLabels) pnlPreviewArea.Controls.Remove(lbl);
            previewItemLabels.Clear();
            // 获取当前设计区所有按钮文本
            List<string> items = new List<string>();
            foreach (var btn in designButtons) items.Add(btn.Text);
            // 动态生成内容标签，靠左对齐
            int y = 180;
            foreach (var item in items)
            {
                Label lbl = new Label
                {
                    Text = item,
                    Location = new Point(60, y), // 靠左对齐
                    Font = new Font("微软雅黑", 12),
                    AutoSize = true
                };
                pnlPreviewArea.Controls.Add(lbl);
                previewItemLabels.Add(lbl);
                y += 40;
            }
        }

        private void ClearAll()
        {
            foreach (var chk in chkPrintItems)
                chk.Checked = false;
            customItems.Clear();
            RefreshDesignButtons();
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            ClearAll();
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            // 1. 创建美化后的图片
            int imageWidth = 400;
            int imageHeight = 500;
            using (Bitmap designBitmap = new Bitmap(imageWidth, imageHeight))
            using (Graphics g = Graphics.FromImage(designBitmap))
            {
                // 设置高质量绘制
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                // 2. 绘制背景和边框
                Rectangle cardRect = new Rectangle(30, 10, imageWidth - 60, imageHeight - 20);
                g.FillRectangle(Brushes.White, cardRect);
                using (Pen borderPen = new Pen(Color.Gray, 2))
                    g.DrawRectangle(borderPen, cardRect);

                // 3. 绘制标题
                string title = txtTitle.Text.Trim();
                using (Font titleFont = new Font("微软雅黑", 22, FontStyle.Bold))
                using (StringFormat titleFormat = new StringFormat { Alignment = StringAlignment.Center })
                {
                    Rectangle titleRect = new Rectangle(30, 40, imageWidth - 60, 40);
                    g.DrawString(title, titleFont, Brushes.Black, titleRect, titleFormat);
                }

                // 4. 绘制分隔线
                int lineY = 90;
                g.DrawLine(Pens.Gray, 60, lineY, imageWidth - 60, lineY);

                // 5. 绘制内容项
                List<string> items = new List<string>();
                foreach (var btn in designButtons) items.Add(btn.Text);
                using (Font itemFont = new Font("微软雅黑", 14))
                {
                    int itemY = lineY + 30;
                    foreach (var item in items)
                    {
                        g.DrawString(item, itemFont, Brushes.Black, 80, itemY);
                        itemY += 36;
                    }
                }

                // 6. 弹出保存对话框
                using (SaveFileDialog sfd = new SaveFileDialog())
                {
                    sfd.Filter = "PNG图片|*.png|JPG图片|*.jpg|所有文件|*.*";
                    sfd.Title = "保存设计区图片";
                    sfd.FileName = txtTitle.Text.Trim() + ".png";
                    
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        // 7. 根据选择的格式保存
                        string extension = Path.GetExtension(sfd.FileName).ToLower();
                        if (extension == ".jpg" || extension == ".jpeg")
                        {
                            designBitmap.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else
                        {
                            designBitmap.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        
                        MessageBox.Show("设计区图片保存成功！", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void BtnPrint_Click(object sender, EventArgs e)
        {
            // 1. 只截取门诊单及其下方内容为图片
            int titleY = lblPreviewTitle.Top;
            int contentHeight = pnlPreviewArea.Height - titleY;
            using (Bitmap fullBmp = new Bitmap(pnlPreviewArea.Width, pnlPreviewArea.Height))
            {
                pnlPreviewArea.DrawToBitmap(fullBmp, new Rectangle(0, 0, pnlPreviewArea.Width, pnlPreviewArea.Height));
                previewBitmap = fullBmp.Clone(new Rectangle(0, titleY, pnlPreviewArea.Width, contentHeight), fullBmp.PixelFormat);
            }

            // 2. 弹出打印对话框
            PrintDocument printDoc = new PrintDocument();
            printDoc.DocumentName = "打印门诊单";
            printDoc.PrintPage += PrintDoc_PrintPage;
            using (PrintDialog dlg = new PrintDialog())
            {
                dlg.Document = printDoc;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    printDoc.Print();
                }
            }
        }

        private void PrintDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            // 1. 打印区域设置
            int pageWidth = e.PageBounds.Width;
            int pageHeight = e.PageBounds.Height;
            int cardWidth = 350;
            int cardHeight = 420;
            int cardX = (pageWidth - cardWidth) / 2;
            int cardY = (pageHeight - cardHeight) / 2;
            Rectangle cardRect = new Rectangle(cardX, cardY, cardWidth, cardHeight);

            // 2. 背景和边框
            e.Graphics.FillRectangle(Brushes.White, cardRect);
            using (Pen borderPen = new Pen(Color.Gray, 2))
                e.Graphics.DrawRectangle(borderPen, cardRect);

            // 3. 标题
            string title = txtTitle.Text.Trim();
            using (Font titleFont = new Font("微软雅黑", 22, FontStyle.Bold))
            using (StringFormat titleFormat = new StringFormat { Alignment = StringAlignment.Center })
            {
                Rectangle titleRect = new Rectangle(cardX, cardY + 30, cardWidth, 40);
                e.Graphics.DrawString(title, titleFont, Brushes.Black, titleRect, titleFormat);
            }

            // 4. 分隔线
            int lineY = cardY + 80;
            e.Graphics.DrawLine(Pens.Gray, cardX + 30, lineY, cardX + cardWidth - 30, lineY);

            // 5. 内容项
            List<string> items = new List<string>();
            foreach (var btn in designButtons) items.Add(btn.Text);
            using (Font itemFont = new Font("微软雅黑", 14))
            {
                int itemY = lineY + 30;
                foreach (var item in items)
                {
                    e.Graphics.DrawString(item, itemFont, Brushes.Black, cardX + 50, itemY);
                    itemY += 36;
                }
            }
        }

        private void BtnAddItem_Click(object sender, EventArgs e)
        {
            string newItem = Microsoft.VisualBasic.Interaction.InputBox("请输入新项目名称:", "添加项目", "");
            if (!string.IsNullOrEmpty(newItem))
            {
                // 检查是否已存在同名按钮或多选框
                if (designButtons.Exists(b => b.Text == newItem) || customItems.Contains(newItem) || Array.Exists(chkPrintItems, c => c.Text == newItem))
                {
                    MessageBox.Show("该项目已存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                customItems.Add(newItem);
                RefreshDesignButtons();
            }
        }
    }
} 